package reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * newInstance的使用
 */
public class Test09 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {

        //1、反射，创建Class对象
        Class c1 = Class.forName("reflection.User");
        //2、构造一个具体的对象，是具体的User类的对象
//        User user = (User) c1.newInstance();  //实际上是调用了无参构造器（如果没有它，就报错了）
//        System.out.println("这是无参构造的newInstance创建出的对象："+user);

        //3、通过有参构造器来创建对象
        Constructor constructor = c1.getDeclaredConstructor(String.class, int.class);
        User user2 = (User) constructor.newInstance("haoming",23);
        System.out.println("这是有参构造的newInstance创建出的对象："+user2);
    }
}
